package com.ldy.core.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.alibaba.fastjson.JSONObject;
import com.ldy.core.util.RequestClient.Response;

import cn.hutool.core.codec.Base64;
import lombok.Data;

/**
 * 天气工具类 抓取 https://www.tianqi.com/langxian/
 */
public class TianqiUtil {

	/**
	 * 天气
	 */
	@Data
	public static class Weather {
		// 天气图片
		private String img;
		// 温度
		private String value;
		// 区间温度
		private String intervalValue;
		// 天气描述
		private String label;
		// 时间
		private String time;
		// 湿度
		private String humidity;

		// 风
		private String wind;
		// 风级别
		private String windLevel;
		// 紫外线
		private String ultraviolet;
		// 空气质量
		private String quality;
		// PM
		private String pm;
		private String amTime;
		private String pmTime;
		
	}

	public static void main(String[] args) throws IOException {
		getWeather("langxian");
	}
	/**
	 * 获取天气
	 * @return
	 * @throws IOException
	 */
	public static Weather getWeather(String code) throws IOException {
		String url = String.format("https://www.tianqi.com/%s/", code);
		Map<String, String> header = new HashMap<String, String>();
		header.put("referer", "https://www.tianqi.com/");
		header.put("User-Agent", "PostmanRuntime/7.42.0");
		Response response = RequestClient.get(url, header, null);
		Document doc = Jsoup.parse(response.getData());
		
		Weather weather = new Weather();
		
		Elements info = doc.select(".weather_info");
		Elements select2 = info.select("dd.week");
		String text = select2.get(0).text();
		weather.setTime(text);
		Elements weatherSel = info.select("dd.weather");
		String img = weatherSel.select("i img").attr("src");
		weather.setImg(getImg(img));
		String text2 = weatherSel.select("p.now b").text();
		weather.setValue(text2);
		String bb = weatherSel.select("span b").text();
		String text3 = weatherSel.select("span").text();
		weather.setLabel(bb);
		weather.setIntervalValue(text3.substring(bb.length()));
		
		Elements shiduEle = info.select("dd.shidu b");
		for (Element e :  shiduEle) {
			String shidu = e.text();
			String[] split = shidu.split("：");
			if ("湿度".equals(split[0])) {
				weather.setHumidity(split[1]);
			} else if ("风向".equals(split[0])) {
				weather.setWind(split[1]);
			} else if ("紫外线".equals(split[0])) {
				weather.setUltraviolet(split[1]);
			}
		}
		

		String kongqi = info.select("dd.kongqi h5").text();
		weather.setQuality(kongqi);

		String pm = info.select("dd.kongqi h6").text();
		weather.setPm(pm);
		String[] split = info.select("dd.kongqi span").html().split("<br>");
		weather.setAmTime(split[0]);
		weather.setPmTime(split[1].replace("\n", ""));
		System.out.println(JSONObject.toJSONString(weather));
		return weather;
//
//		Elements select = doc.select("div.day7");
//		for (Element e : select) {
//			int index = select.indexOf(e);
//			if (index > 4) {
//				break;
//			}
//			String indexStr = (index + 1) + "";
//			System.err.println(indexStr);
//			Weather weather = new Weather();
//			List<String> imgList = e.select("ul.week li img").stream().map(c -> c.attr("src"))
//					.collect(Collectors.toList());
//			List<String> imgList2 = e.select("ul.txt.txt2 li").stream().map(c -> c.text()).collect(Collectors.toList());
//			List<String> imgList3 = e.select("ul.txt.canvas_hour li").stream().map(c -> c.text())
//					.collect(Collectors.toList());
//			List<String> imgList4 = e.select("ul.txt li.mgtop5").stream().map(c -> c.text())
//					.collect(Collectors.toList());
//
//			List<String> imgList22 = e.select("div.zxt_shuju" + indexStr + " ul li span").stream().map(c -> c.text())
//					.collect(Collectors.toList());
//
//			System.out.println(JSONObject.toJSONString(imgList));
//			System.out.println(JSONObject.toJSONString(imgList22));
//			System.out.println(JSONObject.toJSONString(imgList4));
//
////			weather.setImg(imgs.attr("src"));
//
//		}
	}

	/**
	 * 获取天气图片
	 * 
	 * @throws IOException
	 */
	public static String getImg(String url) throws IOException {
//		Map<String, String> header = new HashMap<String, String>();
//		header.put("referer", "https://www.tianqi.com/");
//		header.put("User-Agent", "PostmanRuntime/7.42.0");
//		Response response = RequestClient.get("https:"+url, header, null);
//		return Base64.encode(response.getData().getBytes());
	        HttpURLConnection connection = (HttpURLConnection)  new URL("https:"+url).openConnection();
	        connection.setRequestMethod("GET");
	        connection.setRequestProperty("User-Agent", "Mozilla/5.0");
	        connection.setRequestProperty("referer", "https://www.tianqi.com/");
	        connection.connect();

	        int responseCode = connection.getResponseCode();
	        if (responseCode != HttpURLConnection.HTTP_OK) {
	            throw new IOException("HTTP error code: " + responseCode);
	        }

	        try (InputStream inputStream = connection.getInputStream();
	             ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
	            byte[] buffer = new byte[4096];
	            int bytesRead;
	            while ((bytesRead = inputStream.read(buffer)) != -1) {
	                outputStream.write(buffer, 0, bytesRead);
	            }
	            byte[] imageBytes = outputStream.toByteArray();
	            String base64Image = Base64.encode(imageBytes);
	            return "data:image/png;base64," + base64Image;
	        }
	}
}
